<template>
  <div class="action-items-wrapper">
    <a-popover position="bottom" trigger="click" :width="300" popup-container="body">
      <span class="action-item">
        <SvgIcon name="app" />
        <span class="text">APP下载</span>
      </span>
      <template #content>
        <a-image width="100" :src="iosQRCode" footerPosition="outer" style="margin-right: 12px">
          <template #extra>
            <div class="app-text">iOS下载</div>
          </template>
        </a-image>
        <a-image width="100" :src="androidQRCode" footerPosition="outer">
          <template #extra>
            <div class="app-text">安卓下载</div>
          </template>
        </a-image>
      </template>
    </a-popover>

    <a-popover position="br" trigger="click" :width="300" popup-container="body">
      <span class="action-item">
        <SvgIcon name="export" />
        <span class="text">导出</span>
      </span>
      <template #content>
        <ImportExport />
      </template>
    </a-popover>

    <span v-if="appStore.actionBar.isShowSearch" class="action-item" @click="onShowSearch">
      <SearchIcon />
    </span>
    <!-- 消息 -->
    <a-popover position="br" trigger="click" :width="300" popup-container="body" content-class="sys-message-content">
      <a-badge
        :count="userStore.unreadCount"
        :max-count="999"
        class="action-item"
        :offset="[6, 3]"
        :dot-style="{ background: 'linear-gradient(48deg, #FF5B60 0%, #FF7A66 100%)' }"
      >
        <SvgIcon name="notice" />
        <span class="text">消息</span>
      </a-badge>
      <template #content>
        <MessageContent />
      </template>
    </a-popover>

    <!-- 业务通知 -->
    <MessageModal ref="messageModalRef" />
    <!-- 系统通知 -->
    <SysMessageModal ref="sysMessageModalRef" />
    <span v-if="appStore.actionBar.isShowRefresh" class="action-item" @click="onRefrehRoute">
      <RefreshIcon />
    </span>
    <span v-if="appStore.actionBar.isShowFullScreen && appStore.deviceType !== 'mobile'" class="action-item" @click="onScreenFull">
      <ExpandIcon />
    </span>
    <!-- 设置 -->
    <span class="action-item" @click="onShowSetting" v-if="false">
      <SettingIcon />
    </span>
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, provide, ref } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { useRoute, useRouter } from 'vue-router'
  import {
    IconSettings as SettingIcon,
    IconSearch as SearchIcon,
    IconFullscreen as ExpandIcon,
    IconRefresh as RefreshIcon,
  } from '@arco-design/web-vue/es/icon'
  import { useDebounceFn, useFullscreen } from '@vueuse/core'
  import useEmit from '@/hooks/useEmit'
  import useAppConfigStore from '@/store/modules/app-config'
  import useUserStore from '@/store/modules/user'
  import SvgIcon from '@/components/SvgIcon.vue'
  import androidQRCode from '@/assets/androidQRCode.png'
  import iosQRCode from '@/assets/iosQRCode.png'
  import MessageContent from './components/message-content.vue'
  import ImportExport from './components/import-export.vue'
  import SocketServer from '@/utils/socket-server'
  import { getWsTicket, getMsgList, readMsg } from '@/api/common'
  import MsgQueueEmitter from './components/msg-queue'
  import { SysMessageModal } from './components/outer-import'
  import MessageModal from './components/message-modal.vue'

  export default defineComponent({
    name: 'ActionItems',
    components: {
      SearchIcon,
      SettingIcon,
      ExpandIcon,
      RefreshIcon,
      SvgIcon,
      MessageContent,
      ImportExport,
      SysMessageModal,
      MessageModal,
    },
    setup() {
      const messageModalRef = ref()
      const sysMessageModalRef = ref()
      provide('messageModalRef', messageModalRef)
      provide('sysMessageModalRef', sysMessageModalRef)

      const showSearchContent = ref(false)
      const searchContent = ref('')
      const settingRef = ref()
      const appStore = useAppConfigStore()
      const userStore = useUserStore()
      const router = useRouter()
      const route = useRoute()
      const emitter = useEmit()
      function onShowSearch() {
        emitter?.emit('show-search')
      }
      const { isSupported, enter, isFullscreen, exit } = useFullscreen(document.documentElement)
      function onScreenFull() {
        if (!isSupported) {
          Message.error('当前浏览器不支持全屏操作')
          return false
        }
        if (isFullscreen.value) {
          exit()
        } else {
          enter()
        }
      }
      const debouncedFn = useDebounceFn(() => {
        router.replace({ path: '/redirect' + route.path, query: route.query })
      }, 200)
      function onRefrehRoute() {
        debouncedFn()
      }
      function onShowSetting() {
        emitter?.emit('show-setting')
      }

      // 初始化 WebSocket begin
      let ws: any = null
      const initWS = () => {
        if (ws) return
        const WS_URL = import.meta.env.VITE_WS_URL
        ws = new SocketServer(WS_URL)
        const mqEmitter = new MsgQueueEmitter(router)
        // 登录
        ws.sendLogin = () => {
          getWsTicket().then((res: any) => {
            if (res.code == 200) {
              const ticket = res.result
              ws.WebSocket.sendObj({
                command: 1,
                connect: {
                  ticket,
                },
              })
            }
          })
        }
        // 监听消息
        ws.onListener = (event: any) => {
          userStore.updateUnreadMsgCount()
          mqEmitter.enqueue(event.noticeV2)
        }
      }

      // 获取系统消息
      const getSysMsg = () => {
        const queryParams = {
          pageNumber: 1,
          pageSize: 10,
          noticeType: 2,
          needPcPush: 1,
        }
        getMsgList(queryParams).then((res: any) => {
          if (res.code == 200) {
            const { data } = res.result
            if (data.length > 0) {
              // 显示系统消息弹窗，最后一条系统消息未读时展示消息弹框
              const last_msg = data[0]
              // 未读展示，并已读处理
              if (last_msg.userStatus == 0) {
                readMsg({ id: last_msg.id }).then((res: any) => {
                  if (res.code == 200) {
                    // 刷新列表（清空并获取消息列表）
                    sysMessageModalRef.value?.open(last_msg, 'unread', 1)
                    // 刷新消息数
                    userStore.updateUnreadMsgCount()
                  }
                })
              }
            }
          }
        })
      }

      onMounted(() => {
        // 初始化WebSocket end
        initWS()
        // 初始化消息数
        userStore.updateUnreadMsgCount()
        // 获取系统消息
        getSysMsg()
      })

      return {
        messageModalRef,
        sysMessageModalRef,
        settingRef,
        showSearchContent,
        searchContent,
        userStore,
        appStore,
        androidQRCode,
        iosQRCode,
        onShowSearch,
        onScreenFull,
        onRefrehRoute,
        onShowSetting,
      }
    },
  })
</script>

<style lang="less" scoped>
  .action-items-wrapper {
    position: relative;
    height: 100%;
    display: flex;
    align-items: center;
    z-index: 1;
    .action-item {
      padding: 0 8px;
      min-width: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      font-size: 14px;
      font-weight: 500;
      color: #1d2129;
      line-height: 22px;
      &:hover {
        cursor: pointer;
        background-color: var(--color-secondary-hover);
      }
      :deep(.arco-badge-number, .arco-badge-dot, .arco-badge-text, .arco-badge-custom-dot) {
        transform: translate(10%, 20%);
      }

      .text {
        margin-left: 3px;
        font-size: 14px;
        font-weight: 500;
        color: #1d2129;
        line-height: 22px;
      }
    }
  }
  .app-text {
    margin-left: 10px;
    font-size: 14px;
    font-weight: 500;
    color: #1d2129;
    line-height: 22px;
  }
</style>
